#include "wavefile.h"
#include "shared\dbg.h"


using namespace std;

namespace avlib{
#define RIFF_TAG                    "RIFF"//RIFF
#define WAVE_TAG                    "WAVE"//WAVE
#define FMT__TAG                    "fmt "// FMT
#define DATA_TAG                    "data"//DATA


WaveFile::WaveFile(const char *filename){

	m_total = 0;
	m_filename = filename;

	m_data_sz = 0;
	m_ofs = 0;
}

WaveFile::~WaveFile(){
}

int WaveFile::init(int ch,int samplerate,int samplebits){
	m_ofs =	new std::ofstream(m_filename.c_str(),ios::binary );	

	int tmp4;
	short tmp2;

	int samplebytes = ch *samplebits/8;

	//binary mode can not use << >>
	if(m_ofs){

		//write RIFF
		m_ofs->write(RIFF_TAG,4);
		m_ofs->write((char*)&m_total,4);  //offser :0x04 

		m_ofs->write(WAVE_TAG,4);

		//m_total start from byte 8
		m_total += 4;

		//write FORMAT
		m_ofs->write(FMT__TAG,4);
		tmp4 = 16;m_ofs->write((char*)&tmp4,4); //or 18
		tmp2 = 1;m_ofs->write((char*)&tmp2,2);//pcm u_law
		tmp2 = ch;m_ofs->write((char*)&tmp2,2);
		tmp4 = samplerate;m_ofs->write((char*)&tmp4,4);
		tmp4 = samplerate *samplebytes;m_ofs->write((char*)&tmp4,4);
		tmp2 = samplebytes;m_ofs->write((char*)&tmp2,2);
		tmp2 = samplebits;m_ofs->write((char*)&tmp2,2);
		

		m_total += 16+8;

		//fact?

		//data
		m_ofs->write( DATA_TAG,4);  
		m_ofs->write((char*)&m_data_sz,4); //offset:0x28

		m_total += 8;
	
		m_ofs->flush();

		return 0;
	}else{
		log("can not open file for writting");
		return -1;
	}

	return 0;
}
void WaveFile::add_pcm_data(void *data,size_t len){
	m_ofs->write((char*)data,len);
	m_data_sz += len;
	m_total += len;


	//for safety purpose ,we save toal len and data len

	m_ofs->seekp(0x04,ios::beg);
	m_ofs->write((char*)&m_total,4);

	m_ofs->seekp(0x28,ios::beg);
	m_ofs->write((char*)&m_data_sz,4);

	//seek to end
	m_ofs->seekp(0,ios::end);
	m_ofs->flush();

}
void WaveFile::close(){

	m_ofs->close();
	delete(m_ofs);
	m_ofs = 0;
}
};
